import axios from "axios";
import getShortcutByName from "./getShortcutByName";
import {accessToken, instanceUrl } from "./constants";
import {encodeURIWrapper} from "../../util";

const updateHighlightComments = async (name: string, highlightId: string, comments: string) => {
  const data = await getShortcutByName(name);
  if (!data.shortcut) {
    return;
  }
  const shortcut = data.shortcut;
  const id = shortcut.id;
  const existingViewstates = shortcut.comments.trim().split("\n\n");
  // 从已保存的viewstates中过找到输入的这个viewstate，更新其comments
  let viewstateFounds = existingViewstates.filter((item: string) => {
    const [itemHighlightId] = item.split(";;").slice(0);
    return itemHighlightId === highlightId;
  });
  if (viewstateFounds.length !== 1){
    throw Error(`error: found more than 1 viewstate with highlightId: ${highlightId}`);
  }
  const viewstateFound = viewstateFounds[0];
  const viewstateFoundArray = viewstateFound.split(";;").slice(0, -1);
  viewstateFoundArray.push(encodeURIWrapper(comments.replaceAll("\n > ", "\n")));
  const viewstateUpdated = viewstateFoundArray.join(";;");
  // 剔除老的viewstate，换上新的
  const viewstatesWithoutInput = existingViewstates.filter((item: string) => {
    const [itemHighlightId] = item.split(";;").slice(0);
    return itemHighlightId !== highlightId;
  });
  viewstatesWithoutInput.push(viewstateUpdated);

  const normalizedUrl = instanceUrl.replace(/\/+$/, "");
  const body = JSON.stringify({
    "id": id,
    "comments": viewstatesWithoutInput.join("\n\n"),
  });
  const resp = await axios.put(`${normalizedUrl}/api/v1/shortcuts/${id}?updateMask=comments`, body, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });
  if (resp.status !== 200) {
    throw Error(`updateShortcutViewstate error: ${resp.statusText}, status code ${resp.status}`);
  }
  return resp.data;
}

export default updateHighlightComments;
